use curl::easy::Easy;

const URL: &'static str = "https://projecteuler.net/project/resources/p042_words.txt";

/// [Coded triangle numbers](https://projecteuler.net/problem=42)
fn main() {
    let mut cont = Vec::new();
    {
        let mut easy = Easy::new();
        easy.url(URL).unwrap();
        let mut transfer = easy.transfer();
        transfer
            .write_function(|data| {
                cont.extend_from_slice(data);
                Ok(data.len())
            })
            .unwrap();
        transfer.perform().unwrap();
    }

    let value = String::from_utf8(cont)
        .unwrap()
        .split(",")
        .map(|s| word_value(s.trim_matches('"')))
        .collect::<Vec<_>>();
    let max = *(value.iter().max().unwrap_or(&1));
    let mut triangle = vec![];
    for i in 1.. {
        let x = i * (i + 1) / 2;
        if x > max {
            break;
        }
        triangle.push(x);
    }

    let count = value.iter().filter(|x| triangle.contains(x)).count();
    println!("{:?}", count);
}

fn word_value(s: &str) -> u32 {
    s.chars()
        .map(|c| c.to_digit(36))
        .filter(|x| x.is_some())
        .fold(0, |s, x| s + x.unwrap() - 9)
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn get_value() {
        assert_eq!(word_value("SKY"), 55);
    }
}
